<template>
  <div class="template-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">消息模板列表</span>
          <el-button type="success" @click="handleAdd">
            <el-icon><plus /></el-icon>
            添加消息模板
          </el-button>
        </div>
      </template>

      <!-- 使用搜索栏组件，与项目中其他页面保持一致的风格 -->
      <SearchBar
        :model="searchForm"
        :fields="searchFields"
        @search="searchTemplates"
        @reset="resetSearch"
      >
        <template #actions>
          <div class="search-buttons">
            <div class="left-buttons">
              <el-button type="primary" @click="searchTemplates">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </div>
          </div>
        </template>
      </SearchBar>

      <!-- 使用Element Plus原生表格组件 -->
      <el-table v-loading="loading" :data="templateList" style="width: 100%">
        <el-table-column prop="id" label="ID号" width="80" align="center" />
        <el-table-column prop="name" label="模板标识" width="150" />
        <el-table-column prop="title" label="模板名称" />
        <el-table-column prop="admin_name" label="创建人" width="90" align="center" />
        <el-table-column prop="create_time" label="创建时间" width="150" align="center">
          <template #default="{ row }">
            {{ isTemplate(row) ? formatDate(row.create_time) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <StatusTag v-if="isTemplate(row)" :status="row.status" :config="statusConfig" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <template v-if="isTemplate(row)">
              <el-button size="small" @click="handleView(row)">查看</el-button>
              <el-dropdown>
                <el-button size="small">
                  更多
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleEdit(row)">编辑</el-dropdown-item>
                    <el-dropdown-item v-if="row.status === 1" @click="changeStatus(row, 0)">
                      禁用
                    </el-dropdown-item>
                    <el-dropdown-item v-else @click="changeStatus(row, 1)">启用</el-dropdown-item>
                    <el-dropdown-item @click="handleDelete(row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 使用新创建的分页组件 -->
      <Pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="getTemplateList"
        class="pagination"
      />
    </el-card>

    <!-- 使用统一的抽屉组件实现新建/编辑功能 -->
    <GlobalDrawer
      v-model="editDrawerVisible"
      :title="dialogTitle"
      size="500px"
      direction="rtl"
      @confirm="submitTemplate"
    >
      <!-- 使用新创建的表单组件 -->
      <Form
        ref="templateFormRef"
        :model="templateForm"
        :rules="templateRules"
        :fields="formFields"
        :show-actions="false"
        @submit="submitTemplate"
        @reset="handleEditDrawerClose"
      />
    </GlobalDrawer>

    <!-- 使用统一的抽屉组件实现详情查看功能 -->
    <GlobalDrawer
      v-model="viewDrawerVisible"
      :title="'查看消息模板详情'"
      size="500px"
      direction="rtl"
    >
      <!-- 详情内容 -->
      <div class="detail-container">
        <el-descriptions border :column="1" :title="viewTemplateData.title">
          <el-descriptions-item label="模板名称">{{ viewTemplateData.title }}</el-descriptions-item>
          <el-descriptions-item label="模板标识">{{ viewTemplateData.name }}</el-descriptions-item>
          <el-descriptions-item label="消息标题">
            {{ viewTemplateData.msg_title }}
          </el-descriptions-item>
          <el-descriptions-item label="消息链接">
            {{ viewTemplateData.msg_link || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="消息内容" :span="2">
            <div class="msg-content">{{ viewTemplateData.msg_content }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    getTemplateList as getTemplateListApi,
    saveTemplate as saveTemplateApi,
    setTemplateStatus as setTemplateStatusApi,
    deleteTemplate as deleteTemplateApi,
  } from '@/api/home/template'
  import type { Template } from '@/types/home'

  // 显式注册组件
  import SearchBar from '@/components/base/SearchBar.vue'
  import StatusTag from '@/components/base/BaseStatusTag.vue'
  import Pagination from '@/components/base/BasePagination.vue'
  import Form from '@/components/base/BaseForm.vue'
  import { GlobalDrawer } from '@/components/common'
  import { Plus, ArrowDown } from '@element-plus/icons-vue'

  // 数据相关
  const templateList = ref<Template[]>([])
  const loading = ref(false)

  // 定义类型守卫函数
  const isTemplate = (row: any): row is Template => {
    return (
      typeof row === 'object' &&
      typeof row.status === 'number' &&
      typeof row.create_time === 'number'
    )
  }

  // 定义安全访问函数
  const getTemplateStatus = (row: any): number => {
    return isTemplate(row) ? row.status : 0
  }

  const getTemplateCreateTime = (row: any): number => {
    return isTemplate(row) ? row.create_time : 0
  }

  // 创建计算属性来处理模板列表，增强类型安全性
  const typedTemplateList = computed(() => {
    return templateList.value.map(item => item as Template)
  })

  // 搜索表单
  const searchForm = reactive({
    keywords: '',
  })

  // 搜索字段配置
  const searchFields = [
    {
      prop: 'keywords',
      label: '关键字',
      type: 'input' as const,
      placeholder: '关键字',
      span: 8,
    },
  ]

  // 状态配置
  const statusConfig: any = {
    '1': { type: 'success', text: '正常' },
    '0': { type: 'warning', text: '禁用' },
  }

  // 时间格式化函数，将时间戳转换为年月日格式
  const formatDate = (timestamp: number | string | undefined): string => {
    if (!timestamp || timestamp === 0) return '-'
    const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
    const date = new Date(ts * 1000) // 将秒级时间戳转换为毫秒级
    return date
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '-') // 确保格式为YYYY-MM-DD
  }

  // 分页
  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0,
  })

  // 表单数据
  const templateForm = reactive({
    id: 0,
    title: '',
    name: '',
    msg_title: '',
    msg_link: '',
    msg_content: '',
  })

  // 表单字段配置
  const formFields = [
    {
      prop: 'title',
      label: '模板名称',
      type: 'input' as const,
      placeholder: '请输入模板名称',
    },
    {
      prop: 'name',
      label: '模板标识',
      type: 'input' as const,
      placeholder: '请输入模板标识',
    },
    {
      prop: 'msg_title',
      label: '消息标题',
      type: 'input' as const,
      placeholder: '请输入消息标题',
    },
    {
      prop: 'msg_link',
      label: '消息链接',
      type: 'input' as const,
      placeholder: '请输入消息链接',
    },
    {
      prop: 'msg_content',
      label: '消息内容',
      type: 'textarea' as const,
      placeholder: '请输入消息内容',
    },
  ]

  // 抽屉相关
  const editDrawerVisible = ref(false)
  const viewDrawerVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)
  const viewTemplateData = ref({
    title: '',
    name: '',
    msg_title: '',
    msg_link: '',
    msg_content: '',
  })

  // 表单验证规则
  const templateRules = {
    title: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
    name: [{ required: true, message: '请输入模板标识', trigger: 'blur' }],
  }

  // 表单引用
  const templateFormRef = ref()

  // 搜索模板
  const searchTemplates = () => {
    pagination.currentPage = 1
    getTemplateList()
  }

  // 重置搜索
  const resetSearch = () => {
    searchForm.keywords = ''
    pagination.currentPage = 1
    getTemplateList()
  }

  // 查看模板
  const handleView = (row: Template) => {
    viewTemplateData.value = row
    viewDrawerVisible.value = true
  }

  // 处理分页大小变化
  const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    getTemplateList()
  }

  // 获取模板列表
  const getTemplateList = async () => {
    try {
      loading.value = true
      const params = {
        page: pagination.currentPage,
        limit: pagination.pageSize,
        keywords: searchForm.keywords,
      }

      const response: any = await getTemplateListApi(params)

      // 根据项目规范，直接访问response.code而不是response.data.code
      if (response.code === 0) {
        // 处理两种可能的数据格式
        if (response.data && Array.isArray(response.data)) {
          // 直接是数组格式
          templateList.value = response.data
          pagination.total = response.count || 0
        } else if (response.data && response.data.data) {
          // 分页格式
          templateList.value = response.data.data
          pagination.total = response.data.total || response.count || 0
        } else {
          // 其他情况
          templateList.value = []
          pagination.total = 0
        }
      } else {
        ElMessage.error(response.msg || '获取模板列表失败')
      }
    } catch (error) {
      ElMessage.error('获取模板列表失败')
    } finally {
      loading.value = false
    }
  }

  // 处理添加
  const handleAdd = () => {
    isEdit.value = false
    dialogTitle.value = '添加消息模板'
    templateForm.id = 0
    templateForm.title = ''
    templateForm.name = ''
    templateForm.msg_title = ''
    templateForm.msg_link = ''
    templateForm.msg_content = ''
    editDrawerVisible.value = true
  }

  // 处理编辑
  const handleEdit = (row: Template) => {
    isEdit.value = true
    dialogTitle.value = '编辑消息模板'
    templateForm.id = row.id
    templateForm.title = row.title
    templateForm.name = row.name
    templateForm.msg_title = row.msg_title
    templateForm.msg_link = row.msg_link
    templateForm.msg_content = row.msg_content
    editDrawerVisible.value = true
  }

  // 删除模板
  const handleDelete = async (row: Template) => {
    try {
      await ElMessageBox.confirm('确定要删除该模板吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })

      // 修复API调用，传递正确的参数
      const response: any = await deleteTemplateApi(row.id)

      if (response.code === 0) {
        ElMessage.success('删除成功')
        await getTemplateList()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      // 用户取消删除或出现其他错误
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }

  // 更改状态
  const changeStatus = async (row: Template, status: number) => {
    try {
      // 修复API调用，传递正确的参数
      const response: any = await setTemplateStatusApi(row.id, status)

      if (response.code === 0) {
        ElMessage.success(status === 1 ? '启用成功' : '禁用成功')
        await getTemplateList()
      } else {
        ElMessage.error(response.msg || (status === 1 ? '启用失败' : '禁用失败'))
      }
    } catch (error) {
      ElMessage.error(status === 1 ? '启用失败' : '禁用失败')
    }
  }

  // 提交模板
  const submitTemplate = async () => {
    console.log('submitTemplate called, templateFormRef:', templateFormRef.value)

    if (!templateFormRef.value) {
      console.error('templateFormRef is undefined')
      ElMessage.error('表单引用未找到，请刷新页面重试')
      return
    }

    try {
      console.log('开始表单验证')
      await templateFormRef.value.validate()
      console.log('表单验证通过')

      const params = {
        id: templateForm.id,
        title: templateForm.title,
        name: templateForm.name,
        msg_title: templateForm.msg_title,
        msg_link: templateForm.msg_link,
        msg_content: templateForm.msg_content,
      }

      console.log('准备提交参数:', params)
      const response: any = await saveTemplateApi(params)

      console.log('API响应:', response)
      // 根据项目规范，直接访问response.code而不是response.data.code
      if (response.code === 0) {
        ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
        editDrawerVisible.value = false
        await getTemplateList()
      } else {
        ElMessage.error(response.msg || (isEdit.value ? '编辑失败' : '添加失败'))
        console.error('API返回错误:', response.msg)
      }
    } catch (error) {
      console.error('提交失败的详细错误:', error)
      ElMessage.error(
        isEdit.value
          ? '编辑失败: ' + (error as Error).message
          : '添加失败: ' + (error as Error).message
      )
    }
  }

  // 关闭编辑抽屉
  const handleEditDrawerClose = () => {
    templateFormRef.value?.resetFields()
  }

  // 组件挂载时获取数据
  onMounted(() => {
    getTemplateList()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .detail-container {
    padding: 10px 0;
  }

  .msg-content {
    white-space: pre-wrap;
    word-break: break-all;
  }
</style>
